<template>
  <div class="statistics-chart">
    <h3>{{ name }}数字统计</h3>
    <div v-if="loading" class="loading">加载中...</div>

    <!-- 图表容器区域 -->
    <div class="charts-container" v-else>
      <!-- 前区图表 -->
      <div class="chart-wrapper" v-if="hasFrontData">
        <h4>前区号码出现次数</h4>
        <div ref="frontChart" class="chart"></div>
      </div>

      <!-- 后区图表（仅当有后区且有数据时显示） -->
      <div class="chart-wrapper" v-if="hasBack && hasBackData">
        <h4>后区号码出现次数</h4>
        <div ref="backChart" class="chart"></div>
      </div>

      <!-- 无数据状态 -->
      <div v-if="!hasFrontData && (!hasBack || !hasBackData)" class="no-data">
        暂无统计数据
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, nextTick, onUnmounted } from 'vue'
import * as echarts from 'echarts'
import { getStatistics } from '../api/api'

const props = defineProps({
  type: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  hasBack: {
    type: Boolean,
    default: true
  }
})

// 图表实例引用
const frontInstance = ref(null)
const backInstance = ref(null)
const frontChart = ref(null)
const backChart = ref(null)
const loading = ref(false)
const statsData = ref({
  frontCounts: [],
  backCounts: []
})
const hasFrontData = ref(false)
const hasBackData = ref(false)

// 获取统计数据
const fetchStatistics = async () => {
  loading.value = true
  try {
    const result = await getStatistics(props.type)
    if (result && result.code === 20000 && result.data) {
      // 过滤掉数组的第0条数据
      const filteredFront = result.data.frontCounts.slice(1)
      let filteredBack = []

      // 只有有后区时才处理后区数据
      if (props.hasBack) {
        filteredBack = result.data.backCounts.slice(1)
      }

      statsData.value = {
        frontCounts: filteredFront,
        backCounts: filteredBack
      }

      // 更新数据状态
      hasFrontData.value = Array.isArray(filteredFront) && filteredFront.length > 0
      hasBackData.value = props.hasBack && Array.isArray(filteredBack) && filteredBack.length > 0
    } else {
      statsData.value = { frontCounts: [], backCounts: [] }
      hasFrontData.value = false
      hasBackData.value = false
    }
    nextTick(() => initCharts())
  } catch (error) {
    console.error('获取统计数据失败:', error)
    statsData.value = { frontCounts: [], backCounts: [] }
    hasFrontData.value = false
    hasBackData.value = false
  } finally {
    loading.value = false
  }
}

// 初始化图表
const initCharts = () => {
  nextTick(() => {
    // 销毁旧实例
    if (frontInstance.value) frontInstance.value.dispose()
    if (backInstance.value) backInstance.value.dispose()

    // 通用的tooltip配置
    const tooltipConfig = {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
        label: {
          backgroundColor: '#6a7985',
          color: '#fff',
          padding: [5, 10],
          borderRadius: 2
        }
      },
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#ddd',
      borderWidth: 1,
      borderRadius: 4,
      padding: 10,
      textStyle: {
        color: '#333',
        fontSize: 12
      },
      extraCssText: 'box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);'
    }

    try {
      // 前区图表（始终处理）
      if (frontChart.value && hasFrontData.value) {
        const frontXData = statsData.value.frontCounts.map((_, i) => (i + 1).toString())

        frontInstance.value = echarts.init(frontChart.value)
        frontInstance.value.setOption({
          tooltip: {},
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: frontXData,
              axisLabel: {
                interval: 0
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '出现次数',
              minInterval: 1
            }
          ],
          series: [
            {
              name: '前区号码',
              type: 'bar',
              barWidth: '60%',
              itemStyle: {
                color: '#42b983',
                borderRadius: [4, 4, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  color: '#35956a'
                }
              },
              data: statsData.value.frontCounts
            }
          ]
        })
      }

      // 后区图表（仅当有后区且有数据时处理）
      if (props.hasBack && backChart.value && hasBackData.value) {
        const backXData = statsData.value.backCounts.map((_, i) => (i + 1).toString())

        backInstance.value = echarts.init(backChart.value)
        backInstance.value.setOption({
          tooltip: {},
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: [
            {
              type: 'category',
              data: backXData,
              axisLabel: {
                interval: 0
              }
            }
          ],
          yAxis: [
            {
              type: 'value',
              name: '出现次数',
              minInterval: 1
            }
          ],
          series: [
            {
              name: '后区号码',
              type: 'bar',
              barWidth: '60%',
              itemStyle: {
                color: '#3498db',
                borderRadius: [4, 4, 0, 0]
              },
              emphasis: {
                itemStyle: {
                  color: '#2980b9'
                }
              },
              data: statsData.value.backCounts
            }
          ]
        })
      }

      // 窗口大小调整
      const handleResize = () => {
        frontInstance.value?.resize()
        backInstance.value?.resize()
      }
      window.addEventListener('resize', handleResize)

      onUnmounted(() => {
        window.removeEventListener('resize', handleResize)
      })
    } catch (error) {
      console.error('图表初始化失败:', error)
    }
  })
}

// 监听数据和配置变化
watch([() => statsData.value, () => props.hasBack], () => {
  if (hasFrontData.value || (props.hasBack && hasBackData.value)) {
    nextTick(initCharts)
  }
}, { deep: true })

// 监听类型变化
watch(() => props.type, fetchStatistics)

// 组件挂载
onMounted(() => {
  nextTick(() => fetchStatistics())
})

// 组件卸载
onUnmounted(() => {
  if (frontInstance.value) frontInstance.value.dispose()
  if (backInstance.value) backInstance.value.dispose()
})
</script>

<style scoped>
.statistics-chart {
  padding: 1rem;
  max-width: 1000px;
  margin: 0 auto;
}

.charts-container {
  display: flex;
  flex-direction: column;
  gap: 2rem;
  margin-top: 1rem;
}

.chart-wrapper {
  width: 100%;
  padding: 1rem;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.chart {
  width: 100%;
  height: 400px;
  min-height: 400px;
  background-color: white;
  border-radius: 4px;
}

.loading,
.no-data {
  text-align: center;
  padding: 4rem 2rem;
  color: #666;
}

h3,
h4 {
  text-align: center;
  margin: 0 0 1rem 0;
}
</style>